package com.maotouying.tmtapp.adapter;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.dueeeke.videocontroller.component.PrepareView;
import com.google.gson.Gson;
import com.maotouying.tmtapp.R;
import com.maotouying.tmtapp.api.Api;
import com.maotouying.tmtapp.api.ApiConfig;
import com.maotouying.tmtapp.api.TitleCallback;
import com.maotouying.tmtapp.entity.BaseResponse;
import com.maotouying.tmtapp.entity.VideoEntity;
import com.maotouying.tmtapp.listener.OnItemChildClickListener;
import com.maotouying.tmtapp.listener.OnItemClickListener;
import com.maotouying.tmtapp.view.CircleTransform;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.List;

/**
 * @author mingtai
 * @description 写一个适配器，用来展示数据
 * @time 2020/8/11 0:21
 */

public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    //上下文
    private Context mContext;
    //传过来的对象
    private List<VideoEntity> datas;

    public void setDatas(List<VideoEntity> datas) {
        this.datas = datas; //不用构造器，可以不用反复创建对象
    }

    private OnItemChildClickListener mOnItemChildClickListener;

    private OnItemClickListener mOnItemClickListener;

    public VideoAdapter(Context context) {
        this.mContext = context;
    }

    public VideoAdapter(Context context, List<VideoEntity> datas) {
        this.mContext = context;
        this.datas = datas;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 返回每一项展示的效果(视频的)
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_video_layout, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        //    绑定数据，给控件对象赋值。
        ViewHolder vh = (ViewHolder) holder;
        VideoEntity videoEntity = datas.get(position);

        vh.tvTitle.setText(videoEntity.getVtitle());
        vh.tvAuthor.setText(videoEntity.getAuthor());
        vh.tvcollect.setText(String.valueOf(videoEntity.getCollectNum()));
        vh.tvDz.setText(String.valueOf(videoEntity.getLikeNum())); // 转换为String
        vh.tvcomment.setText(String.valueOf(videoEntity.getCommentNum()));

        // 点赞收藏
        if (videoEntity.getVideoSocialEntity() != null) {
            int likeNum = videoEntity.getVideoSocialEntity().getLikenum();
            int commentNum = videoEntity.getVideoSocialEntity().getCommentnum();
            int collectNum = videoEntity.getVideoSocialEntity().getCollectnum();
            boolean flagLike = videoEntity.getVideoSocialEntity().isFlagLike();
            boolean flagCollect = videoEntity.getVideoSocialEntity().isFlagCollect();
            // 后端返回该用户已经喜欢该视频，true,设置点赞的数量字体颜色，与点赞的图片
            if (flagLike) {
                //设置字体颜色
                vh.tvDz.setTextColor(Color.parseColor("#E21918"));
                // 设置点赞图标为新图标
                vh.imgDianzan.setImageResource(R.mipmap.dianzan_select);
            }
            // 后端返回该用户已经收藏该视频,true,设置收藏的数量字体颜色，与收藏的图片
            if (flagCollect) {
                vh.tvcollect.setTextColor(Color.parseColor("#E21918"));
                vh.imgCollect.setImageResource(R.mipmap.collect_select);
            }

            vh.tvDz.setText(String.valueOf(likeNum));
            vh.tvcomment.setText(String.valueOf(commentNum));
            vh.tvcollect.setText(String.valueOf(collectNum));
            // 为了其他的判断
            vh.flagCollect = flagCollect;
            vh.flagLike = flagLike;
        }

        // 异步加载图片
        Picasso.with(mContext)
                .load(videoEntity.getHeadurl())
                .transform(new CircleTransform()) // 绘制圆形头像
                .into(vh.imgHeader);
        //mThumb 缩略图
        Picasso.with(mContext).load(videoEntity.getCoverurl()).into(vh.mThumb);
        vh.mPosition = position; // 赋值下标

    }

    @Override
    public int getItemCount() {
        // recycleView 列表里面有多少项
        if (datas != null && datas.size() > 0) {
            return datas.size();
        }
        return 0;
    }

    // 写一个类，获取view对象中的每一条数据
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private TextView tvTitle;
        private TextView tvAuthor;
        private TextView tvDz;
        private TextView tvcomment;
        private TextView tvcollect;
        private ImageView imgHeader;

        // 收藏点赞图标
        private ImageView imgCollect;
        private ImageView imgDianzan;

        private boolean flagCollect;
        private boolean flagLike;

        // private ImageView imgCover; 在这里使用播放器自己的
        // 以下三个是播放器专用的
        public ImageView mThumb;
        public PrepareView mPrepareView;
        public FrameLayout mPlayerContainer;
        // 记录下标
        public int mPosition;

        public ViewHolder(@NonNull View view) {
            super(view);
            tvTitle = view.findViewById(R.id.title);
            tvAuthor = view.findViewById(R.id.author);
            tvDz = view.findViewById(R.id.dz);
            tvcomment = view.findViewById(R.id.comment);
            tvcollect = view.findViewById(R.id.collect);
            imgHeader = view.findViewById(R.id.img_header);
            // imgCover = view.findViewById(R.id.img_cover);

            imgCollect = view.findViewById(R.id.img_collect);
            imgDianzan = view.findViewById(R.id.img_like);

            mPlayerContainer = view.findViewById(R.id.player_container);
            mPrepareView = view.findViewById(R.id.prepare_view);
            mThumb = mPrepareView.findViewById(R.id.thumb);

            // 在播放器布局周围设置两个点击事件
            if (mOnItemChildClickListener != null) {
                mPlayerContainer.setOnClickListener(this);
            }
            if (mOnItemClickListener != null) {
                view.setOnClickListener(this);
            }

            /**
             * 点赞、收藏接口
             *     请求地址: /app/videolist/updateCount
             *     请求方法: post
             *     请求头: Content-Type: application/json;charset=UTF-8
             *     请求体实例：
             *         {
             *             "type": 0,  //  （0 评论, 1 收藏, 2 点赞)
             *             "vid": 1,  // 视频id
             *             "flag": true // (true 已收藏, false 未收藏 / true 已点赞, false 未点赞 )
             *         }
             *
             *     响应结果:
             *         ...
             */

            // 创建收藏的点击事件
            imgCollect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int collectNum = Integer.parseInt(tvcollect.getText().toString());
                    // 如果此用户已收藏，点击了按钮做 取消收藏 处理
                    if (flagCollect) {
                        if (collectNum > 0) {
                            // 先做--再赋值
                            tvcollect.setText(String.valueOf(--collectNum));
                            tvcollect.setTextColor(Color.parseColor("#161616"));
                            imgCollect.setImageResource(R.mipmap.collect);
                            // 更新数据库信息
                            upDateCount(datas.get(mPosition).getVid(), 2, !flagCollect);
                        }
                    } else {
                        // 此用户还没有收藏，点击了按钮做 收藏 处理
                        tvcollect.setText(String.valueOf(++collectNum));
                        tvcollect.setTextColor(Color.parseColor("#E21918"));
                        imgCollect.setImageResource(R.mipmap.collect_select);
                        // 更新数据库信息
                        upDateCount(datas.get(mPosition).getVid(), 1, !flagCollect);
                    }
                    // 点击之后，收藏的标志取反
                    flagCollect = !flagCollect;
                }
            });

            imgDianzan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int likeNum = Integer.parseInt(tvDz.getText().toString());
                    // 已点赞
                    if (flagLike) {
                        if (likeNum > 0) {
                            tvDz.setText(String.valueOf(--likeNum));
                            tvDz.setTextColor(Color.parseColor("#161616"));
                            imgDianzan.setImageResource(R.mipmap.dianzan);
                            upDateCount(datas.get(mPosition).getVid(), 2, !flagLike);
                        }
                    } else {//未点赞
                        tvDz.setText(String.valueOf(++likeNum));
                        tvDz.setTextColor(Color.parseColor("#E21918"));
                        imgDianzan.setImageResource(R.mipmap.dianzan_select);
                        upDateCount(datas.get(mPosition).getVid(), 2, !flagLike);
                    }
                    flagLike = !flagLike;
                }
            });

            //通过tag将ViewHolder和itemView绑定
            view.setTag(this);
        }

        // 点击事件的方法
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.player_container) {
                if (mOnItemChildClickListener != null) {
                    mOnItemChildClickListener.onItemChildClick(mPosition);
                }
            } else {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(mPosition);
                }
            }
        }
    }

    // 更新点赞收藏数据
    private void upDateCount(int vid, int type, boolean flag) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("vid", vid);
        params.put("type", type);
        params.put("flag", flag);
        Api.config(ApiConfig.VIDEO_UPDATE_COUNT, params).postRequest(mContext, new TitleCallback() {
            @Override
            public void onSuccess(final String res) {
                Log.e("onSuccess", res);
                Gson gson = new Gson();
                BaseResponse baseResponse = gson.fromJson(res, BaseResponse.class);
                if (baseResponse.getCode() == 0) {

                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    // 设置点击监听
    public void setOnItemChildClickListener(OnItemChildClickListener onItemChildClickListener) {
        mOnItemChildClickListener = onItemChildClickListener;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }


}
